package com.rpa.server.servicerpaserver.expose.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.rpa.secure.servicerpasecure.common.result.Result;
import com.rpa.server.servicerpaserver.crawler.entity.Active;
import com.rpa.server.servicerpaserver.crawler.service.ActiveService;
import com.rpa.server.servicerpaserver.crawler.service.ScoreService;
import com.rpa.server.servicerpaserver.expose.dto.ActiveDto;
import com.rpa.server.servicerpaserver.expose.dto.ScoreDto;
import com.rpa.server.servicerpaserver.util.NameUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.jdbc.SqlBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName ActiveController
 * @Description TODO
 * @Author 86152
 * @Date 2025/2/12 21:15
 * @Version 1.0
 **/
@RestController
@RequestMapping("/api/active")
@Slf4j
@Tag(name = "本系统签到活动相关接口", description = "ActiveController")
public class ActiveController {
    @Autowired
    private ActiveService activeService;
    @Autowired
    private ScoreService scoreService;

    @PostMapping("/getActiveList")
    @Operation(summary = "获取签到活动列表", description = "getActiveList")
    public Result<List<Map<String, Object>>> getActiveList(@RequestBody ActiveDto activeDto) {
        if (Objects.isNull(activeDto)){
            return Result.error("参数不能为空！");
        }
        List<Map<String, Object>> activeList = activeService.getActiveList(activeDto);
        if (CollUtil.isNotEmpty(activeList)) {
           for (Map<String, Object> active : activeList){
               String idStr = MapUtil.getStr(active, "scoreId");
               if (idStr != null) {
                   active.put("scoreId", idStr);
               }
           }
        }
        return Result.success(activeList);
    }

    @PostMapping(value = "/export/downloadActiveList")
    @Operation(summary = "下载签到活动列表", description = "downloadActiveList")
    public void downloadActiveList(@RequestBody ActiveDto activeDto, HttpServletResponse response) {
        if (activeDto == null || activeDto.getFileName() == null || activeDto.getFileName().trim().isEmpty()) {
            log.warn("下载请求参数无效: {}", activeDto);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST); // 400 Bad Request
            return;
        }

        try {
            // 设置 Content-Type 和 Content-Disposition
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");

            // 文件名的 URL 编码
            String fileName = URLEncoder.encode(activeDto.getFileName() + "签到", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 使用 EasyExcel 写入 Excel 文件流到响应输出流
            EasyExcel.write(response.getOutputStream())
                    .head(activeService.head())
                    .sheet(activeDto.getFileName())
                    .doWrite(activeService.dataList(activeDto));

        } catch (Exception e) {
            log.error("下载签到活动列表失败, activeDto: {}", activeDto, e); // 记录异常
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // 500 Internal Server Error
        } finally {
            // 确保关闭输出流
            try {
                response.getOutputStream().close();
            } catch (IOException e) {
                log.error("关闭输出流失败", e);
            }
        }
    }


    @PostMapping("/getActiveListByUserName")
    @Operation(summary = "获取个人签到活动列表详情", description = "getActiveListByUserName")
    public Result<List<Map<String, Object>>> getActiveListByUserName(@RequestBody ActiveDto activeDto) {
        LambdaQueryWrapper<Active> eq = new LambdaQueryWrapper<Active>()
                .eq(Active::getAccountId, activeDto.getAccountId())
                .eq(Active::getCourseId, activeDto.getCourseId())
                .eq(Active::getClazzId, activeDto.getClazzId())
                .eq(Active::getUserName, activeDto.getUserNameEq());
        List<Map<String, Object>> activeList = activeService.listMaps(eq);
        List<Map<String, Object>> camelCaseActiveList = activeList.stream()
                .map(NameUtil::underlineToCamelCase)
                .collect(Collectors.toList());
        List<Map<String, Object>> processedList = camelCaseActiveList.stream()
                .map(map -> {
                    // 将 id 转换为字符串
                    String idStr = MapUtil.getStr(map, "id");
                    if (idStr != null) {
                        map.put("id", idStr);
                    }
                    String signStatus = MapUtil.getStr(map, "signStatus");
                    if (signStatus != null) {
                        if (Objects.equals(signStatus, "0") || Objects.equals(signStatus, "5") ||
                                Objects.equals(signStatus, "11") || Objects.equals(signStatus, "3") ||
                                Objects.equals(signStatus, "4")|| Objects.equals(signStatus, "6")) {
                            map.put("signStatus", "0");
                        }else if (Objects.equals(signStatus, "1")|| Objects.equals(signStatus, "2")){
                            map.put("signStatus", "1");
                        }else if (Objects.equals(signStatus, "7")|| Objects.equals(signStatus, "8")
                                || Objects.equals(signStatus, "12")){
                            map.put("signStatus", "7");
                        }
                    }
                    return map;
                })
                .collect(Collectors.toList());
        return Result.success(processedList);
    }
    @PostMapping("/updateSignStatus")
    @Operation(summary = "更新签到活动列表", description = "updateSignStatus")
    public Result<Boolean> updateSignStatus(@RequestBody List<Active> activeList) {
        if (CollUtil.isEmpty(activeList)){
            return Result.success(true);
        }
        boolean b=true;
        if (CollUtil.isNotEmpty(activeList)) {
            for (Active active : activeList) {
                LambdaUpdateWrapper<Active> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(Active::getId, active.getId())
                        .set(Active::getSignStatus, active.getSignStatus());
                b = activeService.update(updateWrapper)&&b;
            }
        }
        Active active = activeList.get(0);
        ScoreDto scoreDto = new ScoreDto();
        scoreDto.setAccountId(active.getAccountId());
        scoreDto.setCourseId(active.getCourseId());
        scoreDto.setClazzId(active.getClazzId());
        scoreDto.setResetType("2");
         b = scoreService.resetScore(scoreDto)&&b;
        return Result.success(b);
    }

}
